<template>
  <div class="root-table">
    <div class="table-operations">
      <a-button @click="onAdd">添加</a-button>
      <a-button @click="onDels">删除</a-button>
      <a-button @click="onRefresh">刷新</a-button>
      <a-row type="flex">
        <a-col :span="6" :order="4"><a-input-search placeholder="请输入中文名称" @search="onSearchNameZn" enterButton /></a-col>
        <a-col :span="6" :order="3"></a-col>
        <a-col :span="6" :order="2"></a-col>
        <a-col :span="6" :order="1"></a-col>
      </a-row>
    </div>
    <a-table :columns="columns"
      :rowKey="record => record.id"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
    >
      <template slot="url" slot-scope="url">
        <a-avatar shape="square" :size="64" icon="user" :src="url"/>
      </template>
      <template slot="operation" slot-scope="text, record">
        <a @click="onEdit(record)" href="javascript:;">编辑</a>
        <a @click="onDelete(record.id)" href="javascript:;">删除</a>
        <a @click="onExport(record.id)" href="javascript:;">导出</a>
        <a @click="onPublish(record.id)" href="javascript:;">发布备选</a>
      </template>
    </a-table>
    <keep-alive>
    <image-category-add
      ref="collectionForm"
      :title="title"
      :visible="visible"
      :confirmLoading="confirmLoading"
      :record="record"
      @ok="handleOk"
      @cancel="handleCancel"/>
    </keep-alive>
  </div>
</template>
<script>
import Vue from 'vue'
import serv from './ImageCategoryService'
import imageCategoryAdd from './ImageCategoryAdd'
import { Button, Table, Col, Row, Input } from 'ant-design-vue'
Vue.component(Input.Search.name, Input.Search)
Vue.component(Row.name, Row)
Vue.component(Col.name, Col)
Vue.component(Table.name, Table)
Vue.component(Button.name, Button)
const columns = [{
  title: '版本号',
  dataIndex: 'version',
  sorter: false,
  width: '10%'
}, {
  title: '中文名称',
  dataIndex: 'categoryNameZn',
  sorter: false,
  width: '10%'
}, {
  title: '英文名称',
  dataIndex: 'categoryNameEn',
  sorter: false,
  width: '10%'
}, {
  title: '风格',
  dataIndex: 'styleRemark',
  width: '10%'
}, {
  title: '产品类型',
  dataIndex: 'productType',
  width: '10%',
  customRender: (text, record, index) => {
    return {1: '壁画', 2: '墙布', 3: '硬包', 4: '软包', 5: '装饰画', 6: '屏风', 7: '玄关', 8: '纱帘'}[record.productType]
  }
}, {
  title: '是否有版权',
  dataIndex: 'copyright',
  width: '10%',
  customRender: (text, record, index) => {
    return record.copyright ? 'yes' : 'no'
  }
}, {
  title: '封面',
  dataIndex: 'url',
  sorter: false,
  width: '10%',
  scopedSlots: { customRender: 'url' }
}, {
  title: '创建时间',
  dataIndex: 'createTime'
}, {
  title: '是否禁用',
  dataIndex: 'disabled',
  width: '5%',
  customRender: (text, record, index) => {
    return record.disabled ? 'yes' : 'no'
  }
}, {
  title: 'operation',
  dataIndex: '',
  scopedSlots: { customRender: 'operation' }
}]

export default {
  components: {
    imageCategoryAdd
  },
  mounted () {
    this.fetch({
      size: this.pagination.pageSize,
      page: this.pagination.current
    })
  },
  data () {
    return {
      data: [],
      pagination: {
        pageSize: 5,
        current: 1
      },
      selectedRowKeys: [],
      loading: false,
      columns,
      page: {},

      title: '',
      visible: false,
      confirmLoading: false,
      record: {}
    }
  },
  methods: {
    onAdd () {
      this.title = '添加分类'
      this.visible = true
      this.confirmLoading = false
      this.record = {}
    },
    onDelete (id) {
      const _this = this
      this.$confirm({
        title: '友情提示',
        content: '要删除这个分类吗',
        onOk () {
          return new Promise((resolve, reject) => {
            serv.delete(id).then(res => {
              if (res.data.code === 0) {
                const dataSource = [..._this.data]
                _this.data = dataSource.filter(item => item.id !== id)
                resolve()
              } else {
                resolve()
                _this.$message.error(res.data.msg)
              }
            })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel () {}
      })
    },
    onPublish (id) {
      const _this = this
      this.$confirm({
        title: '友情提示',
        content: '要现在发布吗',
        onOk () {
          return new Promise((resolve, reject) => {
            serv.publish(id).then(res => {
              if (res.data.code === 0) {
                resolve()
                _this.$message.success(res.data.msg)
              } else {
                resolve()
                _this.$message.error(res.data.msg)
              }
            })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel () {}
      })
    },
    onExport (id) {
      const _this = this
      this.$confirm({
        title: '友情提示',
        content: '要启动导出吗',
        onOk () {
          return new Promise((resolve, reject) => {
            serv.export(id).then(res => {
              if (res.data.code === 0) {
                resolve()
                _this.$message.success(res.data.msg)
              } else {
                resolve()
                _this.$message.error(res.data.msg)
              }
            })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel () {}
      })
    },
    onEdit (record) {
      this.title = '编辑分类'
      this.visible = true
      this.confirmLoading = false
      this.record = record
    },
    onDels () {
    },
    onRefresh () {
      this.pagination.current = 1
      this.fetch({
        size: this.pagination.pageSize,
        page: this.pagination.current
      })
    },
    handleOk (e) {
      const form = this.$refs.collectionForm.form
      form.validateFields((err, values) => {
        if (err) {
          return
        }
        values.disabled = values.disabled ? 1 : 0
        console.log(values)
        let formData = new FormData()
        for (let key in values) {
          let value = values[key]
          if (value) formData.append(key, value.file ? value.file : value)
        }
        this.confirmLoading = true
        let pageNum = formData.get('id') ? this.pagination.current : 1
        serv.save(formData).then(res => {
          this.confirmLoading = false
          if (res.data.code === 0) {
            form.resetFields()
            this.visible = false
            this.fetch({
              size: this.pagination.pageSize,
              page: pageNum
            })
          } else {
            this.$message.error(res.data.msg)
          }
        })
      })
    },
    handleCancel (e) {
      this.visible = false
      this.record = {}
    },
    onSearchNameZn (value) {
      this.pagination.current = 1
      this.fetch({
        size: this.pagination.pageSize,
        page: this.pagination.current,
        categoryNameZn: value
      })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleTableChange (pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.fetch({
        size: pagination.pageSize,
        page: pagination.current,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters
      })
    },
    async fetch (params = {}) {
      this.loading = true
      this.page = await serv.getPage(params)
      const pagination = { ...this.pagination }
      pagination.total = this.page.totalElements
      // pagination.current = this.page.pageable.pageNumber + 1
      // console.log(this.pagination)
      this.loading = false
      this.selectedRowKeys = []
      this.data = this.page.content
      this.pagination = pagination
    }
  }
}
</script>

<style scoped>
.root-table {
  height: 100%;
}
.table-operations {
  margin-bottom: 16px;
}

.table-operations > button {
  margin-right: 8px;
}
</style>
